
import chardet

# 检测字节流编码
def detect_encoding(raw_data):
    result = chardet.detect(raw_data)
    print(f"编码类型: {result['encoding']}")
    print(f"置信度: {result['confidence']*100:.2f}%")
    print(f"语言: {result.get('language', '未知')}")
    return result['encoding']

# 检测文件编码
def detect_file_encoding(file_path):
    with open(file_path, 'rb') as f:
        return detect_encoding(f.read())

if __name__ == '__main__':
    # 示例1：检测字节流
    text = b'Python chardet\xe5\xba\x93\xe7\xa4\xba\xe4\xbe\x8b'
    detect_encoding(text)
    
    # 示例2：检测文件
    file_path = 'uv.lock'  # 替换为实际文件路径
    encoding = detect_file_encoding(file_path)
    
    # 使用检测结果读取文件
    with open(file_path, 'r', encoding=encoding) as f:
        content = f.read()
        print("\n文件内容前100字符:", content[:100])
